package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;


/**
 * 用户参数解析器
 * 用于解析请求映射方法中声明的当前登录用户的对象信息,注入到请求映射方法声明userinfo参数变量中
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //设置当前解析器只能解析参数类型
    //此次设置为Userinfo
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return (methodParameter.getParameterType() == UserInfo.class)
                && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    //执行这个方法提前:supportsParameter这个方法必须返回为ture
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
       //解析参数并注入参数值
        //简单来说:获取当前登入用户对象,并注入到映射方法的UserInfo参数变量中
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserInfoToken(token);
        //SpringMvc会自动将返回值注入到userinfo变量中
        return user;
    }
}
